const form = document.getElementById('registerForm');
const passwordInput = document.getElementById('password');
const confirmPassword = document.getElementById('confirm-password');
const passwordError = document.getElementById('passwordError');
const sendCodeBtn = document.getElementById('sendCodeBtn');
const emailInput = document.getElementById('email');
const codeInput = document.getElementById('code');

let countdown = 0;
let countdownInterval;

// 发送验证码函数
function sendVerificationCode() {
    const email = emailInput.value.trim();
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email) {
        alert('请输入邮箱地址');
        return;
    }
    if (!emailRegex.test(email)) {
        alert('请输入有效的邮箱地址');
        return;
    }
    sendCodeBtn.disabled = true;
    countdown = 60;
    fetch(`/api/user/send/${encodeURIComponent(email)}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    })
    .then(res => {
        if (!res.ok) throw new Error('发送失败');
        return res.json();
    })
    .then(result => {
        if (result.code === 200) {
            alert('验证码发送成功，请查收邮件');
            startCountdown();
        } else {
            alert(result.message || '验证码发送失败');
            sendCodeBtn.disabled = false;
        }
    })
    .catch(() => {
        alert('验证码发送失败，请重试');
        sendCodeBtn.disabled = false;
    });
}

function startCountdown() {
    sendCodeBtn.textContent = `${countdown}秒后重新发送`;
    countdownInterval = setInterval(() => {
        countdown--;
        if (countdown <= 0) {
            clearInterval(countdownInterval);
            sendCodeBtn.textContent = '发送验证码';
            sendCodeBtn.disabled = false;
        } else {
            sendCodeBtn.textContent = `${countdown}秒后重新发送`;
        }
    }, 1000);
}

if (sendCodeBtn) {
    sendCodeBtn.addEventListener('click', sendVerificationCode);
}

form.addEventListener('submit', (e) => {
    e.preventDefault();
    const email = emailInput.value.trim();
    const password = passwordInput.value;
    const confirm = confirmPassword.value;
    const code = codeInput.value.trim();
    if (!email) {
        alert('请输入邮箱');
        return;
    }
    if (!password) {
        alert('请输入密码');
        return;
    }
    if (!confirm) {
        alert('请确认密码');
        return;
    }
    if (!code) {
        alert('请输入验证码');
        return;
    }
    if (password !== confirm) {
        passwordError.style.display = 'block';
        confirmPassword.classList.add('input-error');
        return;
    } else {
        passwordError.style.display = 'none';
        confirmPassword.classList.remove('input-error');
    }
    const data = {
        avatar: '',
        code: code,
        email: email,
        password: password,
        userName: email // 用邮箱作为用户名
    };
    fetch('/api/user/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(res => {
        if (!res.ok) throw new Error('注册失败');
        return res.json();
    })
    .then(result => {
        if (result.code === 200) {
            if (result.data) {
                localStorage.setItem('token', result.data);
            }
            alert('注册成功！');
            window.location.href = 'login.html';
        } else {
            alert(result.message || '注册失败，请重试');
        }
    })
    .catch(() => {
        alert('注册失败，请重试');
    });
});